import { defineStore } from 'pinia'
import { RouteLocationNormalizedLoaded, RouteRecordRaw } from 'vue-router'
import AsyncRoute from '@/router/modules/system'

export const useNavigateStore = defineStore({
  id: 'useNavigate',
  state: () => ({
    openSidebar: true,

    currentTags: '',
    tagsViewList: [] as Array<{ title: string; path: string; affix: boolean }>,

    roles: ['A','B','C','D'] as Array<string>,
    routes: [] as Array<any>,
  }),
  getters: {},
  actions: {
    addTagsView(route: RouteLocationNormalizedLoaded) {
      if (this.tagsViewList.some((v) => v.path === route.path)) return

      this.tagsViewList.push({
        title: route.meta.title as string,
        path: route.path,
        affix: (route.meta.affix as boolean) ?? false,
      })
    },

    deleteTagsView(path: string) {
      let index = this.tagsViewList.findIndex((v) => v.path === path)
      this.tagsViewList.splice(index, 1)

      
      if (this.currentTags === path) {
        index === 0 ? (index += 1) : index

        if (this.tagsViewList.length === 0) {
          this.tagsViewList.push({
            title: '工作台',
            path: '/dashboard',
            affix: true,
          })
        }

        this.currentTags = this.tagsViewList[index - 1].path
      }
    },

    generateRoutes() {
      let accessedRoutes: RouteRecordRaw[]

      accessedRoutes = this.handleRoute([AsyncRoute])

      this.routes = accessedRoutes
      return accessedRoutes
    },

    handleRoute(routes: RouteRecordRaw[]) {
      const resultRoute: RouteRecordRaw[] = []

      routes.map((route) => {
        if (this.filterPower(route)) {
          if (route.children) {
            route.children = this.handleRoute(route.children)
          }
          resultRoute.push(route)
        }
      })

      return resultRoute
    },

    filterPower(route: RouteRecordRaw) {
      if (route.meta && route.meta.power) {
        return this.roles.includes(route.meta.power as string)
      } else {
        return true
      }
    },
  },
})
